package middleware

import (
	"context"
	"itam/internal/dao"
	"itam/internal/model"
	"itam/internal/service"
)

type sMiddleware struct{}

func init() {
	service.RegisterMiddleware(New())
}

func New() *sMiddleware {
	return &sMiddleware{}
}

// Create 创建
func (s *sMiddleware) Create(ctx context.Context, in model.MiddlewareCreateInput) (out model.MiddlewareCreateOutput, err error) {
	middlewareId, err := dao.Middleware.Ctx(ctx).Data(in).InsertAndGetId()
	if err != nil {
		return out, err
	}
	return model.MiddlewareCreateOutput{Id: int(middlewareId)}, nil
}

// Delete 删除
func (s *sMiddleware) Delete(ctx context.Context, id int) (err error) {
	_, err = dao.Middleware.Ctx(ctx).Where(dao.Middleware.Columns().Id, id).Delete()
	return
}

// Update 修改
func (s *sMiddleware) Update(ctx context.Context, in model.MiddlewareUpdateInput) (err error) {
	_, err = dao.Middleware.Ctx(ctx).Data(in).FieldsEx(dao.Middleware.Columns().Id).Where(dao.Middleware.Columns().Id, in.Id).Update()
	return

}

// GetList 列表查询
func (s *sMiddleware) GetList(ctx context.Context, in model.MiddlewareGetListInput) (out *model.MiddlewareGetListOutput, err error) {
	var m = dao.Middleware.Ctx(ctx)
	out = &model.MiddlewareGetListOutput{
		List: make([]model.MiddlewareListItem, 0),
		Page: in.Page,
		Size: in.Size,
	}
	if in.EnvId > 0 {
		m = m.Where(dao.Middleware.Columns().EnvId, in.EnvId)
	}
	if in.IpAddress != "" {
		m = m.Where(dao.Middleware.Columns().IpAddress, in.IpAddress)
	}
	if in.Name != "" {
		m = m.WhereLike(dao.Middleware.Columns().Name, "%"+in.Name+"%")
	}
	if in.Port > 0 {
		m = m.Where(dao.Middleware.Columns().Port, in.Port)
	}
	m = m.Page(in.Page, in.Size)
	m = m.OrderDesc(dao.Middleware.Columns().Id)

	// 执行查询
	out.Total, err = m.Count()
	if err != nil {
		return out, err
	}
	if out.Total == 0 {
		return out, nil
	}
	// 中间件
	err = m.Scan(&out.List)
	if err != nil {
		return out, err
	}
	// 环境
	rs, err := dao.Env.Ctx(ctx).All()
	if err != nil {
		return out, err
	}
	idMap := rs.MapKeyInt(dao.Env.Columns().Id)

	//fmt.Println(idMap)
	// 循环处理
	for i := 0; i < len(out.List); i++ {
		out.List[i].EnvName = idMap[out.List[i].EnvId]["name"].(string)
	}
	return
}
